Skip to content
c++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

constexpr int N=10005;
std::vector<int>g[N];
int dfn[N],low[N],timer=0;
int scc[N],scc_cnt;
int sccsi[N];
std::vector<int>stk;
bool in_stk[N];
int outdeg[N];

int n,m;
void tarjan(int u){
    dfn[u]=low[u]=++timer;
    stk.push_back(u);
    in_stk[u]=true;

    for(int v:g[u]){
        if(!dfn[v]){
            tarjan(v);
            low[u]=std::min(low[u],low[v]);
        }else if(in_stk[v]){
            low[u]=std::min(low[u],dfn[v]);
        }
    }

    if(dfn[u]==low[u]){
        int v;
        ++scc_cnt;
        do{
            v=stk.back();
            stk.pop_back();
            in_stk[v]=false;
            scc[v]=scc_cnt;
            sccsi[scc_cnt]++;
        }while(u!=v);
    }
}

void fc() {
    std::cin>>n>>m;
    std::vector<std::pair<int,int>>e(m);
    for(auto& [x,y]:e){
        std::cin>>x>>y;
        g[x].push_back(y);
    }

    for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);

    int num=0,si=0;
    for(auto& [x,y]:e){
        int u=scc[x],v=scc[y];
        if(u!=v){
            outdeg[u]++;
        }
    }

    for(int i=1;i<=scc_cnt;i++){
        if(outdeg[i]==0){
            num++;
            si=sccsi[i];
        }
        if(num>1){
            si=0;break;
        }
    }
    std::cout<<si<<"\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    //std::cin>>t;
    while (t--) fc();
    return 0;
}